package crawler;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

import structures.InfoPacket;

//singleton - połaczenie z serwerem od strony klienta
public class CrawlerConnection {
	private Socket _socket;
	private ObjectOutputStream _out = null;
	private ObjectInputStream _in = null;
	private Lock l1 = null;
	private Lock l2 = null;
	// private boolean shuttingDown;
	private int port;
	private String address;
	
	// prywatny konstruktor
	private CrawlerConnection(int port, String address) {
		this.port = port;
		this.address = address;
		l1 = new ReentrantLock();
		l2 = new ReentrantLock();
		try {

			_socket = new Socket(this.address, this.port);
			_in = new ObjectInputStream(_socket.getInputStream());
			_out = new ObjectOutputStream(_socket.getOutputStream());

		} catch (UnknownHostException e1) {
			e1.printStackTrace();
		} catch (IOException e1) {
			e1.printStackTrace();
		}

	}

	
	// jedyna instacja klasy
	private static CrawlerConnection instance = null;

	// klasa zwracająca jedyną instancję systemu
	public static CrawlerConnection getConnector(int port, String address) {
		if (instance == null) {
			instance = new CrawlerConnection(port, address);
		}
		return instance;
	}

	
	// wysyłanie pakietów
	public void sendInfoPacket(InfoPacket packet) {
		
			l1.lock();
			try {
				_out.writeObject(packet);
			} catch (IOException e) {
				 e.printStackTrace();
			}
			l1.unlock();
		
	}

	// odbieranie pakietów
	public InfoPacket receivePacket() throws ClassNotFoundException {
		
		l2.lock();
	
		InfoPacket pck = null;
		try {
			pck = (InfoPacket)_in.readObject();
		} catch (IOException e) {
			e.printStackTrace();
		}
	
		
		l2.unlock();
		return pck;
	}
}
